﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using HtmlAgilityPack;
using System.Threading;
using mshtml;

namespace WindowsFormsApplication15
{
   public partial class MainForm : Form
    {
        #region "Biến cục bộ trong Form"
            List<string> ltReceiptvn = new List<string>();
            List<string> ltReceiptc = new List<string>();
            DataTable dtPayer = new DataTable();
            string ltReceiptText = "";
            string txtUserText = "";
            string InHoaDon = "";
            int txtAgentID;
            int txtUserCreateReceipt;
            int txtUserChangePass;
            int ktDocLoad = 1;
            int txtUserXuatVeNoi;
            bool btTimKiemBool = false;
            bool btTaoMoiBool = false;
            bool btSavePayerBool = false;
            bool btXoaVeBool = false;
            bool dangnhap = false;
            //Khai báo delegate            
            public delegate void SendMessage(string Message);
            public SendMessage Sender;
        #endregion
        public MainForm()
        {
            InitializeComponent();
            //Tạo con trỏ tới hàm GetMessage
            Sender = new SendMessage(GetMessage);
            monthCalendar1.Visible = false;
            btSavePayer.Enabled = false;
            btLuuVe.Enabled = false;
            btXoaVe.Enabled = false;
            btTinhTongTien.Enabled = false;
            btXemHoaDon.Enabled = false;
            btGhiDuLieu.Enabled = false;
            btInHoaDon.Enabled = false;
            btInBangKe.Enabled = false;
            btTaoMoi.Enabled = true;
            pnXuatVeNoi.Visible = true;
        }
        private void GetMessage(string Message)
        {
            //tabControl1.Visible = false;
            txtAgentID = Convert.ToInt32(Message);
            sqlConnection1.Open();
            SqlCommand theCommand = new SqlCommand("SELECT * FROM txtUser WHERE UserID = " + txtAgentID, sqlConnection1);
            SqlDataReader theReader = theCommand.ExecuteReader();
            if (theReader.HasRows)
            {
                theReader.Read();
                txtUserCreateReceipt = Convert.ToInt32(theReader["UserCreateReceipt"]);
                txtUserChangePass = Convert.ToInt32(theReader["UserChangePass"]);
                txtUserXuatVeNoi = Convert.ToInt32(theReader["UserXuatVeNoi"]);
                txtUserText = theReader["UserText"].ToString();
                dangnhap = true;
                theReader.Close();
            }
            lbUser.Text = txtUserText + "  " + txtAgentID + ":" + txtUserCreateReceipt + ":" + txtUserXuatVeNoi + ":" + txtUserChangePass;
            sqlConnection1.Close();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (dangnhap)
            {
                webBrowser1.Document.GetElementById("txtUser").SetAttribute("value", "SLDAILYLLD01");
                webBrowser1.Document.GetElementById("txtPassWord").SetAttribute("value", "212686764");
                webBrowser1.Document.GetElementById("btLogin").InvokeMember("Click");
                dangnhap = false;
            }
            if (btXoaVeBool)
            {
                if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
                {
                    tabControl1.Visible = true;
                }
                btXoaVeBool = false;
            }
            if (ktDocLoad == 7)//Kiem tra so lan chay trang web.
            {
                tabControl1.TabPages.Remove(tabPage2);
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.Load(webBrowser1.DocumentStream);
                //webBrowser1.Document.Body.KeyDown += new HtmlElementEventHandler(Body_KeyDown);                
                #region "Danh sach hoa don tu VNA"
                HtmlNodeCollection ltReceiptnode = doc.DocumentNode.SelectNodes("//*[starts-with(@id,'lbReceipt_i')]");
                if (ltReceiptnode != null)
                {
                    ltReceiptvn.Clear();
                    int n = 0;
                    foreach (HtmlNode item in ltReceiptnode)
                    {
                        ltReceiptvn.Add(item.InnerText);
                        n++;
                    }
                }
                #endregion
                #region "Tuy chon hinh thuc thanh toan la CSH"
                HtmlNodeCollection lbTongTienPaymentList = doc.DocumentNode.SelectNodes("//*[starts-with(@id,'listFopPayment')]");
                if(lbTongTienPaymentList != null)
                {
                    foreach (HtmlNode item in lbTongTienPaymentList)
                    {
                        if (item.InnerText == "CSH")
                        {
                            webBrowser1.Document.GetElementById(item.Id).InvokeMember("Click");
                        }
                    }
                }
                #endregion
                #region "Lay thong tin tong tien va don vi tien"
                HtmlNode lbTongtienNode = doc.DocumentNode.SelectSingleNode("//*[@id='txtAmountFop_text']");
                HtmlNode lbCurrencyNode = doc.DocumentNode.SelectSingleNode("//*[@id='txtFopCurrency_text']");
                if (lbTongtienNode.GetAttributeValue("value", string.Empty) != "" && lbCurrencyNode.GetAttributeValue("value", string.Empty) != "")
                {
                    lbTongtien.Text = lbTongtienNode.GetAttributeValue("value", string.Empty) + " " + lbCurrencyNode.GetAttributeValue("value", string.Empty);
                }
                #endregion
                #region "Tao moi hoa don"
                if (btTaoMoiBool)
                {
                    HtmlNode ltReceiptfirstnode = doc.DocumentNode.SelectSingleNode("//*[@id='lbReceipt_i0']");
                    try
                    {
                        sqlConnection1.Open();
                        //Insert hoa don moi.
                        SqlCommand theCommandInsert = sqlConnection1.CreateCommand();
                        theCommandInsert.CommandText =
                        "INSERT INTO txtReceipt" +
                        "(ReceiptName, ReceiptCreate, AgentID)" +
                        "VALUES" +
                        "(@ReceiptName, @ReceiptCreate, @AgentID)";
                        theCommandInsert.Parameters.Add("@ReceiptName", SqlDbType.VarChar, 6);
                        theCommandInsert.Parameters.Add("@ReceiptCreate", SqlDbType.Int);
                        theCommandInsert.Parameters.Add("@AgentID", SqlDbType.Int);
                        theCommandInsert.Parameters["@ReceiptName"].Value = ltReceiptfirstnode.InnerText;
                        theCommandInsert.Parameters["@ReceiptCreate"].Value = 1;
                        theCommandInsert.Parameters["@AgentID"].Value = txtAgentID;
                        theCommandInsert.ExecuteNonQuery();
                        //Show du lieu ra, bao gom so moi.
                        string day = monthCalendar1.SelectionStart.Day.ToString();
                        string month = monthCalendar1.SelectionStart.Month.ToString();
                        string year = monthCalendar1.SelectionStart.Year.ToString();
                        List<string> ltReceiptsql = new List<string>();
                        string theTaoMoi = "SELECT ReceiptName FROM txtReceipt WHERE " +
                            "DAY(ReceiptDate)='" + day + "' AND " +
                            "MONTH(ReceiptDate)='" + month + "' AND " +
                            "YEAR(ReceiptDate)='" + year + "' AND " +
                            "AgentID = " + txtAgentID;
                        SqlCommand theComTaoMoi = new SqlCommand(theTaoMoi, sqlConnection1);
                        SqlDataReader theReaderTaoMoi = theComTaoMoi.ExecuteReader();
                        ltReceiptsql.Clear();
                        while (theReaderTaoMoi.Read())
                        {
                            ltReceiptsql.Add(theReaderTaoMoi["ReceiptName"].ToString());
                        }
                        ltReceiptsql.Reverse();
                        ltReceipt.Items.Clear();
                        foreach (string item in ltReceiptsql)
                        {
                            ltReceipt.Items.Add(item);
                        }
                        ltReceipt.SelectedItem = ltReceiptfirstnode.InnerText;
                        //MessageBox.Show(ltReceiptfirstnode.InnerText);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.StackTrace);
                    }
                    finally
                    {
                        sqlConnection1.Close();
                        //sqlConnection1.Dispose();
                    }
                    //btTimKiemBool = true;//Show du lieu ra, bao gom so moi.
                    btTaoMoiBool = false;//Ket thuc tao moi, khong cho tao moi chay nua.
                }
                #endregion
                #region "Danh sach hoa don tu CSDL tuong ung dai ly"
                if (btTimKiemBool)
                {
                    sqlConnection1.Open();
                    string day = monthCalendar1.SelectionStart.Day.ToString();
                    string month = monthCalendar1.SelectionStart.Month.ToString();
                    string year = monthCalendar1.SelectionStart.Year.ToString();
                    List<string> ltReceiptsql = new List<string>();
                    string theTimKiem = "SELECT ReceiptName FROM txtReceipt WHERE " +
                        "DAY(ReceiptDate)='" + day + "' AND " +
                        "MONTH(ReceiptDate)='" + month + "' AND " +
                        "YEAR(ReceiptDate)='" + year + "' AND " +
                        "AgentID = " + txtAgentID;
                    SqlCommand theComTimKiem = sqlConnection1.CreateCommand();
                    theComTimKiem.CommandText = theTimKiem;
                    SqlDataReader theReaderTimKiem = theComTimKiem.ExecuteReader();
                    ltReceiptsql.Clear();
                    while (theReaderTimKiem.Read())
                    {
                        ltReceiptsql.Add(theReaderTimKiem["ReceiptName"].ToString());
                    }
                    ltReceiptsql.Reverse();
                    ltReceipt.Items.Clear();
                    foreach (string item in ltReceiptsql)
                    {
                        ltReceipt.Items.Add(item);
                    }
                    sqlConnection1.Close();
                    btTimKiemBool = false;//Ket thuc tiem kiem, khong cho tiem kiem chay lan nua.
                }
                #endregion
                #region "Luu thong tin nguoi thanh toan"
                if (btSavePayerBool)
                {
                    HtmlElement txtPayerName = webBrowser1.Document.GetElementById("txtPayer");
                    HtmlElement txtPayerCode = webBrowser1.Document.GetElementById("txtVatCode");
                    HtmlElement txtPayerAdd = webBrowser1.Document.GetElementById("txtAddress");
                    HtmlElement txtPayerUser = webBrowser1.Document.GetElementById("txtCustomer");
                    sqlConnection1.Open();
                    //Luu thong tin Payer
                    SqlCommand theComSavePayer = sqlConnection1.CreateCommand();
                    theComSavePayer.CommandText =
                        "INSERT INTO txtPayer" +
                        "(PayerName, PayerCode, PayerAdd, AgentID, ReceiptName, PayerUser)" +
                        "VALUES" +
                        "(@PayerName, @PayerCode, @PayerAdd, @AgentID, @ReceiptName, @PayerUser)";
                    theComSavePayer.Parameters.Add("@PayerName", SqlDbType.NText);
                    theComSavePayer.Parameters.Add("@PayerCode", SqlDbType.VarChar, 50);
                    theComSavePayer.Parameters.Add("@PayerAdd", SqlDbType.NText);
                    theComSavePayer.Parameters.Add("@AgentID", SqlDbType.Int);
                    theComSavePayer.Parameters.Add("@ReceiptName", SqlDbType.VarChar, 6);
                    theComSavePayer.Parameters.Add("@PayerUser", SqlDbType.NText);
                    theComSavePayer.Parameters["@PayerName"].Value = txtPayerName.GetAttribute("value").ToString();
                    theComSavePayer.Parameters["@PayerCode"].Value = txtPayerCode.GetAttribute("value").ToString();
                    theComSavePayer.Parameters["@PayerAdd"].Value = txtPayerAdd.GetAttribute("value").ToString();
                    theComSavePayer.Parameters["@AgentID"].Value = txtAgentID;
                    theComSavePayer.Parameters["@ReceiptName"].Value = ltReceipt.Text;
                    theComSavePayer.Parameters["@PayerUser"].Value = txtPayerUser.GetAttribute("value").ToString();
                    theComSavePayer.ExecuteNonQuery();
                    //Xac nhan da thao tac Payer
                    SqlCommand theCom = sqlConnection1.CreateCommand();
                    theCom.CommandText = "UPDATE txtReceipt SET ReceiptSavePayer=ReceiptSavePayer+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
                    theCom.ExecuteNonQuery();
                    sqlConnection1.Close();
                    btSavePayerBool = false;
                }
                #endregion
                #region "Doi mat khau"
                if (txtUserChangePass == 0)
                {
                    textBox4.Enabled = false;
                    textBox5.Enabled = false;
                    textBox6.Enabled = false;
                    btXacNhanDoiMatKhau.Enabled = false;
                    btHuyLenhDoiMatKhau.Enabled = false;
                    label11.Text = "Đại lý không có quyền đổi mật khẩu";
                }
                #endregion
                #region "Xuat ve noi"
                if (txtUserXuatVeNoi == 1)
                {
                    pnXuatVeNoi.Visible = false;
                }
                #endregion
                #region "Tinh trang button"
                HtmlNode btSavePayernode = doc.DocumentNode.SelectSingleNode("//*[@id='SaveReceipt']");
                if (btSavePayernode.GetAttributeValue("disabled", string.Empty) == "disabled" || ltReceipt.Text == "") { btSavePayer.Enabled = false; }
                else { btSavePayer.Enabled = true; }
                HtmlNode btLuuVenode = doc.DocumentNode.SelectSingleNode("//*[@id='btSaveTicket']");
                if (btLuuVenode.GetAttributeValue("disabled", string.Empty) == "disabled" || ltReceipt.Text == "") { btLuuVe.Enabled = false; }
                else { btLuuVe.Enabled = true; }
                HtmlNode btXoaVenode = doc.DocumentNode.SelectSingleNode("//*[@id='delTicket']");
                if (btXoaVenode.GetAttributeValue("disabled", string.Empty) == "disabled" || ltReceipt.Text == "") { btXoaVe.Enabled = false; }
                else { btXoaVe.Enabled = true; }
                HtmlNode btTinhTongTiennode = doc.DocumentNode.SelectSingleNode("//*[@id='btnSaveFop']");
                if (btTinhTongTiennode.GetAttributeValue("disabled", string.Empty) == "disabled" || ltReceipt.Text == "") { btTinhTongTien.Enabled = false; }
                else { btTinhTongTien.Enabled = true; }
                HtmlNode btGhiDuLieunode = doc.DocumentNode.SelectSingleNode("//*[@id='btCalFop']");
                if (btGhiDuLieunode.GetAttributeValue("disabled", string.Empty) == "disabled" || ltReceipt.Text == "") { btGhiDuLieu.Enabled = false; }
                else { btGhiDuLieu.Enabled = true; }
                #endregion
                #region "In hoa don"
                if (ltReceipt.Text != "")
                {
                    sqlConnection1.Open();
                    SqlCommand theCommand = sqlConnection1.CreateCommand();
                    theCommand.CommandText =
                        "SELECT * FROM txtReceipt WHERE ReceiptName='" + ltReceipt.Text + "'";
                    SqlDataReader theReader = theCommand.ExecuteReader();
                    theReader.Read();
                    if (theReader["ReceiptIn"].ToString() == "0")
                    {
                        if (theReader["ReceiptGhiTien"].ToString() != "0" && theReader["ReceiptTongTien"].ToString() != "0")
                        {
                            btInHoaDon.Enabled = true;
                        }
                    }
                    else
                    {
                        btInHoaDon.Enabled = true;
                    }
                    theReader.Close();
                    sqlConnection1.Close();
                }
                #endregion
                #region "In bang ke"
                HtmlNode theSoVeQuyDinhBangKe = doc.DocumentNode.SelectSingleNode("//*[@id='lbReceiptDetails_i7']");
                if (theSoVeQuyDinhBangKe != null)
                {
                    btInBangKe.Enabled = true;
                }
                #endregion
                #region "Cac thong so don le"
                tbDate.Text = monthCalendar1.SelectionStart.ToString("dd/MM/yyyy");
                ltReceiptText = ltReceipt.Text;//Lay so hoa don dang lua chon
                ktDocLoad = 1;//Reset so lan chay trang web.
                tabControl1.Visible = true;//Hien thi chuong trinh.
                #endregion
                #region "Lay thong tin Payer"
                //sqlConnection1.Open();
                //SqlCommand theComPayer = sqlConnection1.CreateCommand();
                //theComPayer.CommandText = "SELECT * FROM txtPayer WHERE AgentID='" + txtAgentID + "' AND PayerSet=1";
                //SqlDataReader theReaderPayer = theComPayer.ExecuteReader();
                //if (theReaderPayer.HasRows)
                //{
                //    dtPayer.Clear();
                //    cbPayer.Items.Clear();
                //    dtPayer.Load(theReaderPayer);
                //    //for(int i = 0; i < dtPayer.Rows.Count; i++)
                //    //{
                //    //    cbPayer.Items.Add(dtPayer.Rows[i][0].ToString());
                //    //}
                //    cbPayer.DataSource = dtPayer;
                //    cbPayer.DisplayMember = "PayerName";
                //    cbPayer.ValueMember = "PayerID";
                //}
                //sqlConnection1.Close();
                #endregion
            }            
            ktDocLoad++;            
        }

        private void cbPayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            //int idcombo = cbPayer.SelectedIndex;
            //MessageBox.Show(idcombo.ToString());
            //webBrowser1.Document.GetElementById("txtPayer_text").SetAttribute("value", dtPayer.Rows[idcombo][0].ToString());
            //webBrowser1.Document.GetElementById("txtPayer").SetAttribute("value", dtPayer.Rows[idcombo][0].ToString());
            //webBrowser1.Document.GetElementById("txtVatCode_text").SetAttribute("value", dtPayer.Rows[idcombo][1].ToString());
            //webBrowser1.Document.GetElementById("txtVatCode").SetAttribute("value", dtPayer.Rows[idcombo][1].ToString());
            //webBrowser1.Document.GetElementById("txtAddress_text").SetAttribute("value", dtPayer.Rows[idcombo][2].ToString());
            //webBrowser1.Document.GetElementById("txtAddress").SetAttribute("value", dtPayer.Rows[idcombo][2].ToString());
            //webBrowser1.Document.GetElementById("txtCustomer_text").SetAttribute("value", dtPayer.Rows[idcombo][3].ToString());
            //webBrowser1.Document.GetElementById("txtCustomer").SetAttribute("value", dtPayer.Rows[idcombo][3].ToString());
        }

        private void btTinhTongTien_Click(object sender, EventArgs e)
        {
            #region "Cap nhat thao tac tinh tong tien"            
            sqlConnection1.Open();
            SqlCommand theCom = sqlConnection1.CreateCommand();
            theCom.CommandText = "UPDATE txtReceipt SET ReceiptTongTien=ReceiptTongTien+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
            theCom.ExecuteNonQuery();
            sqlConnection1.Close();
            #endregion
            #region "Hien thi dung so tien CSH"
            webBrowser1.Document.GetElementById("btCalFop").InvokeMember("Click");
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(webBrowser1.DocumentStream);
            HtmlNodeCollection lbTongTienPaymentList = doc.DocumentNode.SelectNodes("//*[starts-with(@id,'listFopPayment')]");
            foreach (HtmlNode i in lbTongTienPaymentList)
            {
                if (i.InnerText == "CSH")
                {
                    webBrowser1.Document.GetElementById(i.Id).InvokeMember("Click");
                }
            }
            #endregion
        }

        void tbDate_Click(object sender, EventArgs e)
        {
            monthCalendar1.Visible = !monthCalendar1.Visible;
        }

        private void btXemHoaDon_Click(object sender, EventArgs e)
        {
            WebBrowser wb = new WebBrowser();
            TabPage tab = new TabPage("Review Sale Receipt " + ltReceipt.Text);
            wb.Navigate("http://agent2.vietnamair.com.vn/Form/PreviewSaleReceipt.aspx?&pid=LLD" + monthCalendar1.SelectionStart.ToString("yyMMdd") + ltReceipt.Text);
            wb.Dock = DockStyle.Fill;
            Button btXemHoaDonClose = new Button();
            btXemHoaDonClose.Location = new Point(700, 6);
            btXemHoaDonClose.Size = new Size(75, 23);
            btXemHoaDonClose.Text = "Close";
            btXemHoaDonClose.UseVisualStyleBackColor = true;
            btXemHoaDonClose.Click += new System.EventHandler(this.btXemHoaDonClose_Click);
            tab.Controls.Add(btXemHoaDonClose);
            tab.Controls.Add(wb);
            tabControl1.TabPages.Add(tab);
            tabControl1.SelectedTab = tab;
        }

        private void btXemHoaDonClose_Click(object sender, EventArgs e)
        {
            tabControl1.TabPages.Remove(tabControl1.SelectedTab);
        }

        private void btTaoMoi_Click(object sender, EventArgs e)
        {
            if (txtUserCreateReceipt == 1)
            {
                sqlConnection1.Open();
                SqlCommand theCommand = new SqlCommand("SELECT ReceiptName, CONVERT(varchar(10),ReceiptDate,103) AS ReceiptDate FROM txtReceipt WHERE ReceiptIn = 0 AND AgentID = " + txtAgentID, sqlConnection1);
                SqlDataReader theReader = theCommand.ExecuteReader();
                if (theReader.Read())
                {
                    string hoaDonChuaHoangThanh = "";
                    //while (theReader.Read())
                    //{
                        hoaDonChuaHoangThanh += "Hoa don " + theReader["ReceiptName"] + " ngay " + theReader["ReceiptDate"] + " chua hoan thanh!\r\n";
                    //}
                    MessageBox.Show(hoaDonChuaHoangThanh);
                }
                else
                {
                    //MessageBox.Show("Khong co hoa don trong, duoc quyen tao hoa don!");
                    btTaoMoiBool = true;                    
                    tabControl1.Visible = false;
                    webBrowser1.Document.GetElementById("btnNewReceipt").InvokeMember("Click");
                    //webBrowser1.Document.GetElementById("btnSearch").InvokeMember("Click");
                }
                sqlConnection1.Close();
            }
            else
            {
                MessageBox.Show("Lien he nhan vien ho tro de kiem tra quyen xuat hoa don!");
            }
        }

        private void btLoadVe_Click(object sender, EventArgs e)
        {
            //Khi Load ve thi webbrowser khong Load nen thuc hien ngay tren button Load ve
            #region "Gan so ve cho so ve tren browser"
            HtmlElement txtTicketNo = webBrowser1.Document.GetElementById("txtTicketNo");
            txtTicketNo.SetAttribute("value", tbTicketNo.Text);
            #endregion
            #region "Kiem tra nut save Payer"
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(webBrowser1.DocumentStream);
            HtmlNode btLuuVenode = doc.DocumentNode.SelectSingleNode("//*[@id='btSaveTicket']");
            #endregion
            sqlConnection1.Open();
            //Khong co chon hoa don hoac hoa don khong co phat sinh moi thi Save Ticket khong bao gom so hoa don
            if (ltReceipt.Text == "" || btLuuVenode.GetAttributeValue("disabled", string.Empty) == "disabled")
            {
                SqlCommand theCommand = sqlConnection1.CreateCommand();
                theCommand.CommandText =
                    "INSERT INTO txtTicket" +
                    "(TicketName, AgentID)" +
                    "VALUES" +
                    "(@TicketName, @AgentID)";
                theCommand.Parameters.Add("@TicketName", SqlDbType.VarChar);
                theCommand.Parameters.Add("@AgentID", SqlDbType.Int);
                theCommand.Parameters["@TicketName"].Value = txtTicketNo.GetAttribute("value");
                theCommand.Parameters["@AgentID"].Value = txtAgentID;
                theCommand.ExecuteNonQuery();
            }
            else
            {
                SqlCommand theCommand = sqlConnection1.CreateCommand();
                theCommand.CommandText =
                    "INSERT INTO txtTicket" +
                    "(TicketName, AgentID, ReceiptName)" +
                    "VALUES" +
                    "(@TicketName, @AgentID, @ReceiptName)";
                theCommand.Parameters.Add("@TicketName", SqlDbType.VarChar);
                theCommand.Parameters.Add("@AgentID", SqlDbType.Int);
                theCommand.Parameters.Add("@ReceiptName", SqlDbType.VarChar, 6);
                theCommand.Parameters["@TicketName"].Value = tbTicketNo.Text;
                theCommand.Parameters["@AgentID"].Value = txtAgentID;
                theCommand.Parameters["@ReceiptName"].Value = ltReceipt.Text;
                theCommand.ExecuteNonQuery();
                SqlCommand theCom = sqlConnection1.CreateCommand();
                theCom.CommandText = "UPDATE txtReceipt SET ReceiptLoadTicket=ReceiptLoadTicket+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
                theCom.ExecuteNonQuery();
            }
            sqlConnection1.Close();
            webBrowser1.Document.GetElementById("btnLoadTicket").InvokeMember("Click");
        }

        private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
        {
            tbDate.Text = monthCalendar1.SelectionStart.ToString("dd/MM/yyyy");
            monthCalendar1.Visible = false;
        }

        private void btTimKiem_Click(object sender, EventArgs e)
        {
            tabControl1.Visible = false;
            HtmlElement dateInput = webBrowser1.Document.GetElementById("txtReceiptCreadDate_dateInput");
            HtmlElement btnSearch = webBrowser1.Document.GetElementById("btnSearch");
            dateInput.SetAttribute("value", monthCalendar1.SelectionStart.ToString("yyyy-MM-dd-00-00-00"));
            btnSearch.InvokeMember("Click");
            btTimKiemBool = true;
        }

        private void ltReceipt_SelectedIndexChanged(object sender, EventArgs e)
        {
            //tabControl1.Visible = false;
            //ltReceiptText = ltReceipt.Text;
            int i = ltReceiptvn.IndexOf(ltReceipt.Text);
            string testb = "lbReceipt_i" + i.ToString();
            if (testb != "lbReceipt_i-1")
            {
                //MessageBox.Show(i.ToString() + "\r\n" + ltReceipt.Text);
                if (ltReceipt.Text != ltReceiptText)
                {
                    //MessageBox.Show("Chon so hoa don moi");
                    tabControl1.Visible = false;
                    webBrowser1.Document.GetElementById(testb).InvokeMember("Click");
                    btXemHoaDon.Enabled = true;
                    //lbTongtienBool = true;
                }
                //else
                //{
                //    MessageBox.Show("Chon lai so cu roi");
                //}
            }
            else
            {
                MessageBox.Show("Hóa đơn không tồn tại hoặc bị hủy!");
            }
        }
        
        private void btSavePayer_Click(object sender, EventArgs e)
        {
            webBrowser1.Document.GetElementById("SaveReceipt").InvokeMember("Click");
            tabControl1.Visible = false;
            btSavePayerBool = true;
        }

        private void btLuuVe_Click(object sender, EventArgs e)
        {
            //Khi Luu ve thi webbrowser khong Load nen thuc hien ngay tren button Luu ve
            #region ""
            HtmlElement txtTicketNoSave = webBrowser1.Document.GetElementById("txtTicketNo");
            #endregion
            sqlConnection1.Open();
            SqlCommand theCommand = sqlConnection1.CreateCommand();
            theCommand.CommandText =
                "INSERT INTO txtTicket" +
                "(TicketName, AgentID, ReceiptName, TicketSave)" +
                "VALUES" +
                "(@TicketName, @AgentID, @ReceiptName, @TicketSave)";
            theCommand.Parameters.Add("@TicketName", SqlDbType.VarChar);
            theCommand.Parameters.Add("@AgentID", SqlDbType.Int);
            theCommand.Parameters.Add("@ReceiptName", SqlDbType.VarChar, 6);
            theCommand.Parameters.Add("@TicketSave", SqlDbType.Int);
            theCommand.Parameters["@TicketName"].Value = txtTicketNoSave.GetAttribute("value");
            theCommand.Parameters["@AgentID"].Value = txtAgentID;
            theCommand.Parameters["@ReceiptName"].Value = ltReceipt.Text;
            theCommand.Parameters["@TicketSave"].Value = 1;
            theCommand.ExecuteNonQuery();
            SqlCommand theCom = sqlConnection1.CreateCommand();
            theCom.CommandText = "UPDATE txtReceipt SET ReceiptSaveTicket=ReceiptSaveTicket+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
            theCom.ExecuteNonQuery();
            sqlConnection1.Close();
            tbTicketNo.Text = "";
            webBrowser1.Document.GetElementById("btSaveTicket").InvokeMember("Click");
        }

        private void btXoaVe_Click(object sender, EventArgs e)
        {
            //Khi Xoa ve thi webbrowser khong Load nen thuc hien ngay tren button Xoa ve
            HtmlElement txtTicketNoDelete = webBrowser1.Document.GetElementById("txtTicketNo");
            tabControl1.Visible = false;
            sqlConnection1.Open();
            SqlCommand theCommand = sqlConnection1.CreateCommand();
            theCommand.CommandText =
                "INSERT INTO txtTicket" +
                "(TicketName, AgentID, ReceiptName, TicketSave)" +
                "VALUES" +
                "(@TicketName, @AgentID, @ReceiptName, @TicketSave)";
            theCommand.Parameters.Add("@TicketName", SqlDbType.VarChar);
            theCommand.Parameters.Add("@AgentID", SqlDbType.Int);
            theCommand.Parameters.Add("@ReceiptName", SqlDbType.VarChar, 6);
            theCommand.Parameters.Add("@TicketSave", SqlDbType.Int);
            theCommand.Parameters["@TicketName"].Value = txtTicketNoDelete.GetAttribute("value");
            theCommand.Parameters["@AgentID"].Value = txtAgentID;
            theCommand.Parameters["@ReceiptName"].Value = ltReceipt.Text;
            theCommand.Parameters["@TicketSave"].Value = 2;
            theCommand.ExecuteNonQuery();
            SqlCommand theCom = sqlConnection1.CreateCommand();
            theCom.CommandText = "UPDATE txtReceipt SET ReceiptDeleteTicket=ReceiptDeleteTicket+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
            theCom.ExecuteNonQuery();
            sqlConnection1.Close();
            tbTicketNo.Text = "";
            webBrowser1.Document.GetElementById("delTicket").InvokeMember("Click");
            HtmlElementCollection links = webBrowser1.Document.GetElementsByTagName("a");
            links[2].InvokeMember("click");
            btXoaVeBool = true;
            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
        }

        private void btGhiDuLieu_Click(object sender, EventArgs e)
        {
            #region "Cap nhat thao tac ghi tien"
            sqlConnection1.Open();
            SqlCommand theCom = sqlConnection1.CreateCommand();
            theCom.CommandText = "UPDATE txtReceipt SET ReceiptGhiTien=ReceiptGhiTien+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
            theCom.ExecuteNonQuery();
            sqlConnection1.Close();
            #endregion
            webBrowser1.Document.GetElementById("btnSaveFop").InvokeMember("Click");            
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            monthCalendar1.Visible = !monthCalendar1.Visible;
        }

        private void btHuyLenhDoiMatKhau_Click(object sender, EventArgs e)
        {
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
        }

        private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
                HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
                IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
                element.text = "window.alert = function () { }";
                //element.text = "window.alert('abc')";
                head.AppendChild(scriptEl);
            }
        }

        private void btXacNhanDoiMatKhau_Click(object sender, EventArgs e)
        {
            if (txtUserChangePass != 0)
            {
                if (textBox4.Text != "" && textBox5.Text != "" && textBox6.Text != "")
                {
                    if (string.Compare(textBox5.Text, textBox6.Text) == 0)
                    {
                        sqlConnection1.Open();
                        SqlCommand theCommand = new SqlCommand("SELECT UserPass AS Pass FROM txtUser WHERE UserID = " + txtAgentID, sqlConnection1);
                        SqlDataReader theReader = theCommand.ExecuteReader();
                        theReader.Read();
                        if (string.Compare(textBox4.Text, theReader["Pass"].ToString()) == 0)
                        {
                            theReader.Close();
                            SqlCommand theCommandUpdate = sqlConnection1.CreateCommand();
                            theCommandUpdate.CommandText = "UPDATE txtUser SET UserPass = '" + textBox6.Text + "' WHERE UserID = " + txtAgentID;
                            theCommandUpdate.ExecuteNonQuery();
                            textBox4.Text = "";
                            textBox5.Text = "";
                            textBox6.Text = "";
                            MessageBox.Show("Đổi mật khẩu thành công!");
                        }
                        else
                        {
                            MessageBox.Show("\"Mật khẩu đang dùng\" không đúng!");
                        }
                        sqlConnection1.Close();
                    }
                    else
                    {
                        MessageBox.Show("\"Nhập lại mật khẩu mới\" không giống \"Mật khẩu mới\"!");
                    }
                }
                else
                {
                    MessageBox.Show("Chưa nhập mật khẩu!");
                }
            }
            else
            {
                MessageBox.Show("Đại lý không có quyền đổi mật khẩu!");
            }
        }

        private void btInHoaDon_Click(object sender, EventArgs e)
        {
            sqlConnection1.Open();
            SqlCommand theCommand = sqlConnection1.CreateCommand();
            theCommand.CommandText = "UPDATE txtReceipt SET ReceiptIn=ReceiptIn+1 WHERE ReceiptName='" + ltReceipt.Text + "'";
            theCommand.ExecuteNonQuery();
            SqlCommand theComd = sqlConnection1.CreateCommand();
            theComd.CommandText =
                "INSERT INTO txtPrint" +
                "(ReceiptName, AgentID)" +
                "VALUES" +
                "(@ReceiptName, @AgentID)";
            theComd.Parameters.Add("@ReceiptName", SqlDbType.VarChar);
            theComd.Parameters.Add("@AgentID", SqlDbType.Int);
            theComd.Parameters["@ReceiptName"].Value = ltReceipt.Text;
            theComd.Parameters["@AgentID"].Value = txtAgentID;
            theComd.ExecuteNonQuery();
            sqlConnection1.Close();
            WebBrowser wbInHoaDon = new WebBrowser();
            TabPage tab = new TabPage("Sale Receipt " + ltReceipt.Text);
            //wbInHoaDon.Navigate("http://agent2.vietnamair.com.vn/FrmSaleReport.aspx?&pid=LLD" + monthCalendar1.SelectionStart.ToString("yyMMdd") + ltReceipt.Text + "&lien=2");
            string address = "http://agent2.vietnamair.com.vn/FrmSaleReport.aspx?&pid=LLD" + monthCalendar1.SelectionStart.ToString("yyMMdd") + ltReceipt.Text + "&lien=2";
            wbInHoaDon.Url = new Uri(address);
            wbInHoaDon.NewWindow += new System.ComponentModel.CancelEventHandler(wbInHoaDon_NewWindow);
            wbInHoaDon.Dock = DockStyle.Fill;
            Button btInHoaDonClose = new Button();
            btInHoaDonClose.Location = new Point(700, 6);
            btInHoaDonClose.Size = new Size(75, 23);
            btInHoaDonClose.Text = "Close";
            btInHoaDonClose.UseVisualStyleBackColor = true;
            btInHoaDonClose.Click += new System.EventHandler(this.btInHoaDonClose_Click);
            tab.Controls.Add(btInHoaDonClose);            
            tab.Controls.Add(wbInHoaDon);
            tabControl1.TabPages.Add(tab);
            tabControl1.SelectedTab = tab;
        }

        private void btInBangKe_Click(object sender, EventArgs e)
        {
            WebBrowser wbInBangKe = new WebBrowser();
            TabPage tab = new TabPage("Bang ke hoa don " + ltReceipt.Text);
            wbInBangKe.Navigate("http://agent2.vietnamair.com.vn/Form/FrmBangKe.aspx?pid=LLD" + monthCalendar1.SelectionStart.ToString("yyMMdd") + ltReceipt.Text + "&lien=2&type=1");
            wbInBangKe.Dock = DockStyle.Fill;            
            Button btInBangKeClose = new Button();
            btInBangKeClose.Location = new Point(700, 6);
            btInBangKeClose.Size = new Size(75, 23);
            btInBangKeClose.Text = "Close";
            btInBangKeClose.UseVisualStyleBackColor = true;
            btInBangKeClose.Click += new System.EventHandler(this.btInBangKeClose_Click);
            tab.Controls.Add(btInBangKeClose);
            tab.Controls.Add(wbInBangKe);
            tabControl1.TabPages.Add(tab);
            tabControl1.SelectedTab = tab;
            wbInBangKe.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(wbInBangKe_DocumentCompleted);            
        }

        private void wbInHoaDon_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void wbInBangKe_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser wbInBangKe = (WebBrowser)sender;
            wbInBangKe.ShowPrintDialog();
        }

        private void btInHoaDonClose_Click(object sender, EventArgs e)
        {
            tabControl1.TabPages.Remove(tabControl1.SelectedTab);
        }

        private void btInBangKeClose_Click(object sender, EventArgs e)
        {
            tabControl1.TabPages.Remove(tabControl1.SelectedTab);
        }
   }
}
